package com.jessechanrui.template.req18.pdf.itext;

import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.RectangleReadOnly;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

import bank.bod.exception.BaseException;
import cn.com.agree.afa.svc.javaengine.AppLogger;
import edm.IBS_KKL.IBSKKLSERVE.bean.Svr0838BatchInfo;
import edm.IBS_KKL.IBSKKLSERVE.bean.Svr0838WageDetail;
import edm.IBS_KKL.IBSKKLSERVE.bean.Svr0838WageInfo;
import edm.IBS_KKL.IBSKKLSERVE.dao.Svr0838BatchInfoMapper;
import edm.IBS_KKL.IBSKKLSERVE.dao.Svr0838WageDetailMapper;
import ibs.server.kkl.scene.consts.KklTradeConsts;
import ibs.server.kkl.scene.enums.KklErrorCodeEnum;
import platform.database.mybatis.util.MybatisUtils;

/**
 * 
 * @author 901000057 itext1.x版本
 *
 */
public class CreatePdfGen {

	/**
	 * 生成
	 * @param file
	 * @throws BaseException 
	 */
	public void create(String file, Svr0838WageInfo wage) throws BaseException {
		try {
			Rectangle pageSize = new RectangleReadOnly(width, height);
			Document doc = new Document(pageSize, pl, pr, pt, pb);
			PdfWriter.getInstance(doc, new FileOutputStream(file));
			
			// 字体
			BaseFont baseFont = BaseFont.createFont(KklTradeConsts.FONT_PATH + "simfang.ttf",
					BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
						
			doc.open();

			// 标题
			PdfPTable title = new PdfPTable(1);
			float[] widthTitle = {1f};
			title.setWidths(widthTitle);
			title.setHorizontalAlignment(Element.ALIGN_LEFT);
			title.setWidthPercentage(widthPc);
			title.setSpacingAfter(titlePaddingBottom);
			Font titleFont = new Font(baseFont, titleWordSize, Font.BOLD);
			addTableCell("工人工资专项代发结果详情", titleFont, 20.0F, PdfPCell.ALIGN_CENTER, PdfPCell.NO_BORDER, title);
			
			// 头部信息
			PdfPTable head = new PdfPTable(4);
			float[] widthHead = {0.5f, 1f, 0.5f, 1f};
			head.setWidths(widthHead);
			head.setHorizontalAlignment(Element.ALIGN_LEFT);
			head.setWidthPercentage(widthPc);
			head.setSpacingAfter(titlePaddingBottom);
			Font headFont = new Font(baseFont, contentWordSize, Font.BOLD);
			
			Svr0838BatchInfoMapper batchMapper = MybatisUtils.getMapperToAutoCommit(Svr0838BatchInfoMapper.class);
			List<Svr0838BatchInfo> batchInfos = batchMapper.select4Receipt(wage.getPlatDate(), wage.getPlatSerialNo());
			
			Map<String, String> map = new LinkedHashMap<String, String>();
			map.put("渠道流水号：", batchInfos.get(0).getChannelSerialNo());
			map.put("批次号：", batchInfos.get(0).getBatchNo());
			map.put("专户账号：", batchInfos.get(0).getAcctNo());
			map.put("专户名称：", batchInfos.get(0).getAcctName());
			map.put("总笔数：", batchInfos.get(0).getTotalNum());
			map.put("总金额（元）：", batchInfos.get(0).getTotalAmount());
			map.put("交易日期：", batchInfos.get(0).getPlatDate());
			map.put("", "");
			
			map.forEach((k, v) -> {
				addTableCell(k, headFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.NO_BORDER, head);
				addTableCell(v, headFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.NO_BORDER, head);
			});
			
			// 正文标题
			PdfPTable content = new PdfPTable(9);
			float[] widthContent = {1.05f, 1.05f, 1.05f, 1.35f, 0.9f, 1.1f, 0.7f, 0.9f, 0.9f};
			String[] contentTitle = {"序号", "收款人姓名", "开户行名称", "收款人银行卡号", "发放月份", "申请发薪金额", "备注", "交易状态", "失败原因"};
			content.setWidths(widthContent);
			content.setHorizontalAlignment(Element.ALIGN_LEFT);
			content.setWidthPercentage(widthPc);
			Font contentFont = new Font(baseFont, contentWordSize, Font.BOLD);
			for (String item : contentTitle) {
				addTableCell(item, contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
			}
			
			// 正文
			rowData(wage, batchInfos.get(0), contentFont, content);
			
			doc.add(title);
			doc.add(head);
			doc.add(content);
			
			doc.close();
			
			footer(file);
			
			AppLogger.info("生成成功");
		} catch (Exception e) {
			AppLogger.error(e);
			throw new BaseException(KklErrorCodeEnum.CREATE_PDF_ERR.getCode(), KklErrorCodeEnum.CREATE_PDF_ERR.getMsg());
		}
	}
	
	/**
	 * 页脚
	 * @param file
	 * @throws BaseException
	 */
	private void footer(String file) throws BaseException {
		PdfReader reader = null;
		FileOutputStream fos = null;
		PdfStamper stamper = null;
		try {
			reader = new PdfReader(file);
			fos = new FileOutputStream(file + "_bak");
			stamper = new PdfStamper(reader, fos);
			
			BaseFont baseFont = BaseFont.createFont(KklTradeConsts.FONT_PATH + "经典宋体简.ttf",
					BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			
			float y = 50.0F;
			for (int i = 1; i <= reader.getNumberOfPages(); i++) {
				PdfContentByte content = stamper.getOverContent(i);
				
				content.beginText();
				content.setFontAndSize(baseFont, contentWordSize);
				String prefix = String.format("共%s页/第%s页", reader.getNumberOfPages(), i);
				float x = pl + (((width - (pl + pr)) * 0.78F) / 2) - ((prefix.length() * contentWordSize * 0.8F) / 2);
				content.showTextAligned(PdfContentByte.ALIGN_LEFT, prefix, x, y, 0);
				content.endText();
			}
		} catch (Exception e) {
			AppLogger.error(e);
			throw new BaseException(KklErrorCodeEnum.CREATE_FOOTER_ERR.getCode(), KklErrorCodeEnum.CREATE_FOOTER_ERR.getMsg());
		} finally {
			try {
				if (stamper != null) {
					stamper.close();
				}
				if (fos != null) {
					fos.close();
				}
				if (reader != null) {
					reader.close();
				}
				
				File orgFile = new File(file);
				orgFile.delete();
				
				File bkFile = new File(file + "_bak");
				bkFile.renameTo(orgFile);
			} catch (Exception e) {
				AppLogger.error(e);
				throw new BaseException(KklErrorCodeEnum.CREATE_FOOTER_ERR.getCode(), KklErrorCodeEnum.CREATE_FOOTER_ERR.getMsg());
			}
		}
	}
	
	/**
	 * 行
	 * @param detailInfos
	 * @param contentFont
	 * @param content
	 */
	public void rowData(Svr0838WageInfo wage, Svr0838BatchInfo batchInfo, Font contentFont, PdfPTable content) {
		
		String idxPlatDate = "";
		String idxPlatSerialNo = "";
		while(true) {
			Svr0838WageDetailMapper mapper = MybatisUtils.getMapperToAutoCommit(Svr0838WageDetailMapper.class);
			List<Svr0838WageDetail> detailInfos = mapper.select4Acct(idxPlatDate, idxPlatSerialNo, wage.getPlatDate(), wage.getPlatSerialNo(), null, KklTradeConsts.DEFAULT_PAGESIZE);
			
			if (detailInfos == null || detailInfos.size() == 0) {
				AppLogger.info("查无处理明细数据");
				break;
			}
			
			for (Svr0838WageDetail detail : detailInfos) {
				addTableCell(detail.getSerNum(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getName(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getOpeningBank(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getBankCardNum(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(batchInfo.getSalaryDate(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getApplyForSalaryAmount(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getRemarks(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getHostStatus() == null ? "" : KklTradeConsts.HOTS_STATUS_1.equals(detail.getHostStatus()) ? "成功" : "失败", contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
				addTableCell(detail.getErrorMsg(), contentFont, 14.0F, PdfPCell.ALIGN_LEFT, PdfPCell.BOX, content);
			}
			
			idxPlatDate = detailInfos.get(detailInfos.size() - 1).getPlatDate();
			idxPlatSerialNo = detailInfos.get(detailInfos.size() - 1).getPlatSerialNo();
		}
		
	}

	/**
	 * 单元格
	 * @param text
	 * @param font
	 * @param lineHeight
	 * @param align
	 * @param border
	 * @param table
	 */
	public void addTableCell(String text, Font font, float lineHeight, int align, int border, PdfPTable table) {
		Chunk chunk = new Chunk(text == null ? "" : text, font);
		chunk.setTextRise(1.75F);
		Phrase para = new Phrase(chunk);
		PdfPCell cell = new PdfPCell(para);
		cell.setBorder(border);
		cell.setHorizontalAlignment(align);
//		cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
//		cell.setFixedHeight(lineHeight);
		table.addCell(cell);
	}

	private float width;
	private float height;
	private float pl;
	private float pr;
	private float pt;
	private float pb;
	private float widthPc; // 宽%
	private float titlePaddingBottom; // 标题下间距
	private float titleWordSize; // 标题字体大小
	private float contentWordSize; // 正文字体大小
	
	public CreatePdfGen(float width, float height, float pl, float pr, float pt, float pb, float widthPc,
			float titlePaddingBottom, float titleWordSize, float contentWordSize) {
		this.width = width;
		this.height = height;
		this.pl = pl;
		this.pr = pr;
		this.pt = pt;
		this.pb = pb;
		this.widthPc = widthPc;
		this.titlePaddingBottom = titlePaddingBottom;
		this.titleWordSize = titleWordSize;
		this.contentWordSize = contentWordSize;
	}
}
